package com.gcloud.mesh.asset.timer;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.header.msg.asset.ListDeviceMsg;
import com.gcloud.mesh.header.msg.asset.UpdateNodeMsg;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.monitor.service.StatisticsCheatService;
import com.gcloud.mesh.monitor.service.StatisticsService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ServerStorageCapacityTimer {
	@Autowired
	private IAssetService assetService;

	@Autowired
	private StatisticsService statisticsService;

	@Autowired
	private StatisticsCheatService statisticsCheatService;

	@Scheduled(fixedDelay = 1000 * 60)
	public void work() {

		log.info("[ServerEnergyConversion] 计算服务器存储容量开始 START");

		ListDeviceMsg msg = new ListDeviceMsg();
		msg.setType(6);
		List<DeviceItemVo> nodes = assetService.listDevice(msg);

		for (DeviceItemVo node : nodes) {
			String totalStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_STORAGE_TOTAL.getMeter(),
					node.getId());
			String availableStr = statisticsCheatService.latestSample(MonitorMeter.SERVER_STORAGE_AVAILABLE.getMeter(),
					node.getId());

			if (!totalStr.isEmpty() && !availableStr.isEmpty()) {
				Double total = Double.parseDouble(totalStr);
				Double available = Double.parseDouble(availableStr);

				if (total - available <= 0) {
					continue;
				}
				Float storageCapacity = (float) ((total - available) / total);

				UpdateNodeMsg updateNodeMsg = new UpdateNodeMsg();
				updateNodeMsg.setId(node.getId());
				updateNodeMsg.setStorageCapacity(storageCapacity);
				assetService.updateNode(updateNodeMsg, "");
			}
		}

		log.info("[ServerEnergyConversion] 计算服务器存储容量结束 END");
	}
}
